package com.sdjzu.wangfuying.hellospringboot.aspect;

import com.sdjzu.wangfuying.hellospringboot.util.SpringBootUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class LoginVerifyAspect {
    private final Logger logger = LoggerFactory.getLogger(LoginVerifyAspect.class);
    private static final String POINT_CUT = "@annotation(com.sdjzu.wangfuying.hellospringboot.annotation.LoginRequired)";

    @Pointcut(POINT_CUT)
    public void loginVerifyPointCut() {

    }

    @Around(POINT_CUT)
    public Object interceptor(ProceedingJoinPoint point) {

        //正在被通知的方法相关信息
        MethodSignature signature = (MethodSignature) point.getSignature();
        //获取被拦截的方法
        Method method = signature.getMethod();
        //获取被拦截的方法名
        String methodName = method.getName();
        //返回的结果
        Object result = null;
        //获取RequestAttributes
        HttpServletRequest request = SpringBootUtil.getRequest();

        //返回方法参数
        if (!isLogin(request)) {
            //JsonResult与ResultCode是我自己封装的返回类及enum类
            result = "没有登录";
        }
        try {
            if (result == null)
                // 一切正常的情况下，继续执行被拦截的方法
                result = point.proceed();
        } catch (Throwable e) {
            result = "发生异常：" + e.getMessage();
        }

        return result;
    }

    /**
     * 判断方法是否需要登录
     *
     * @param request
     * @return
     */
    private boolean isLogin(HttpServletRequest request) {
        return request.getSession().getAttribute("token") != null;
    }
}
